package com.gzhryc.shared_device.oem.micro.queue.work;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrder;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderService;

import java.util.Date;
import java.util.List;

/**
 * 执行密码线程完成检查
 * @version 20240416
 */
public class PCLCacheFinishCheckRunnable implements Runnable{

    static Logger log = Logger.getLogger(PCLCacheFinishCheckRunnable.class);

    OperateInfo operateInfo;

    public PCLCacheFinishCheckRunnable(OperateInfo operateInfo){
        this.operateInfo = operateInfo;
    }

    @Override
    public void run() {
        try {
            List<PCLOrder> deviceOrderList = RedisCacheManager.findWorkingPCLDeviceOrder();
            if (deviceOrderList != null && deviceOrderList.size() > 0) {
                for (PCLOrder deviceOrder : deviceOrderList) {
                    //从数据库获取设备订单信息，避免缓存脏数据
                    PCLOrder temp = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                    if(temp == null){
                        log.error("未找到便捷线充的设备订单，缓存信息：{{0:json}}",deviceOrder);
                        continue;
                    }else{
                        deviceOrder = temp;
                    }

                    //TODO 检查订单状态
                    //检查结束时间是否已到
                    if (deviceOrder.getEndDate() != null) {
                        Date now = new Date();
                        if (now.after(deviceOrder.getEndDate())) {
                            //时间已到
                            operateInfo.setOperateNote("便携线充订单服务时间已到");
                            try {
                                //从数据库获取设备订单信息，避免缓存脏数据
                                deviceOrder = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                int result = PCLOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder, deviceOrder.getPayMoney(), PayServiceFactory.self(), operateInfo);
                                if (result == 2) {
                                    //订单已经完成，同步会员订单
                                    deviceOrder = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                    if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(), deviceOrder.getMoney(), deviceOrder.getPayMoney()
                                            , deviceOrder.getWalletMoney())) {
                                        log.error("便携线充订单完成，但同步会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                                    }

                                    JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                                    if (producer != null) {
                                        OrderFinishEvent event = new OrderFinishEvent(EBusinessType.PCL.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(), operateInfo);
                                        KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                        producer.send(kafkaMessage);
                                    }else{
                                        log.error("未初始化消息队列，订单{{0}}未触发完成事件",deviceOrder.getTradeNo());
                                    }
                                }
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            } finally {
                            	//清理缓存，避免定时器重复处理
                                RedisCacheManager.removeWorkingPCLDeviceOrder(deviceOrder.getTradeNo());
                            }
                        }
                    } else {
                        operateInfo.setOperateNote("便携线充订单没有结束时间，异常结束");
                        try {
                            if (PCLOrderService.self(deviceOrder.getCreateDate()).close(deviceOrder, operateInfo)) {
                                //订单已经完成，同步会员订单
                                deviceOrder = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(), deviceOrder.getMoney(), deviceOrder.getPayMoney()
                                        , deviceOrder.getWalletMoney())) {
                                    log.error("便携线充订单完成，但同步会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                                }
                            }else {
                            	log.error("便携线充订单没有结束时间，关闭订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                        	//清理缓存，避免定时器重复处理
                            RedisCacheManager.removeWorkingPCLDeviceOrder(deviceOrder.getTradeNo());
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }
}
